package com.bowen.spike.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import com.bowen.spike.common.Result;
import com.bowen.spike.context.UserContext;
import com.bowen.spike.entity.UserVoucher;
import com.bowen.spike.mapper.UserVoucherMapper;
import com.bowen.spike.service.IUserVoucherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bowen.spike.task.AsynchronousTask;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.UUID;

/**
 * <p>
 * 用户优惠券关联表 服务实现类
 * </p>
 *
 * @author bowen
 * @since 2025-04-28
 */
@Service
@RequiredArgsConstructor
public class UserVoucherServiceImpl extends ServiceImpl<UserVoucherMapper, UserVoucher> implements IUserVoucherService {

    // redis客户端
    private final RedisTemplate<String, String> redisTemplate;

    //redisson客户端
    private static final DefaultRedisScript<Long> VOUCHER_SCRIPT;

    static {
        // 读取脚本文件并初始化脚本
        VOUCHER_SCRIPT = new DefaultRedisScript<>();
        VOUCHER_SCRIPT.setLocation(new ClassPathResource("Voucher.lua"));
        VOUCHER_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result lightningDealCoupons(Long voucherId) {

        long result = 0;
        try {
            // 开始执行lua脚本
            result = redisTemplate.execute(
                    VOUCHER_SCRIPT,
                    Collections.emptyList()
                    , voucherId.toString(), UserContext.getUserId().toString()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (result == -2) {
            return Result.error("优惠券已过期");
        }
        if (result == -3) {
            return Result.error("优惠券已下架");
        }
        if (result == 0) {
            return Result.error("库存不足");
        }
        if (result == -1) {
            return Result.error("不可重复抢卷");
        }

        //执行到这里说明Redis已经产生了用户优惠劵记录，接下来异步执行插入数据库即可
        long userVoucherId = IdUtil.getSnowflakeNextId();
        UserVoucher userVoucher = new UserVoucher()
                .setVoucherId(voucherId)
                .setId(userVoucherId)
                .setUserId(UserContext.getUserId());

        // 异步执行插入任务
        AsynchronousTask.addTask(() -> save(userVoucher));
        return Result.ok();
    }


}
